import 'package:campus_vision/routes/app_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../providers/device_providers.dart';
import '../../widgets/device/device_card.dart';

class DeviceListPage extends ConsumerWidget {
  const DeviceListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 👇 监听设备列表 Provider
    final devicesAsync = ref.watch(deviceListProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('设备列表'),
        centerTitle: true,
      ),
      body: devicesAsync.when(
        // 加载中状态
        loading: () {
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
        // 错误状态
        error: (error, stackTrace) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.error, size: 48, color: Colors.red),
                const SizedBox(height: 16),
                Text(
                  '加载失败: ${error.toString()}',
                  textAlign: TextAlign.center,
                  style: const TextStyle(color: Colors.red),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => ref.refresh(deviceListProvider.future),
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        },
        // 成功状态
        data: (devices) {
          if (devices.isEmpty) {
            return const Center(
              child: Text('暂无设备'),
            );
          }
          return RefreshIndicator(
            onRefresh: () => ref.refresh(deviceListProvider.future),
            child: ListView.builder(
              itemCount: devices.length,
              itemBuilder: (context, index) {
                final device = devices[index];
                return DeviceCard(
                  device: device,
                  onTap: () {
                    // 跳转到播放页（假设设备 id 不为空）
                    if (device.id != null) {
                      context.push("${AppRoute.play}/${device.id}");
                    }
                  },
                );
              },
            ),
          );
        },
      ),
    );
  }
}
